<!DOCTYPE html>
<html
  lang="zh"
  xmlns:th="http://www.thymeleaf.org"
  xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
  <head>
    <th:block th:include="include :: header('监测数据列表')" />
  </head>

  <body class="gray-bg">
    <div class="container-div">
      <div class="row">
        <div class="col-sm-12 search-collapse">
          <form id="formId">
            <div class="select-list">
              <ul>
                <li>
                  风机：<select name="fanId">
                    <option value="" style="display: none">请选择</option>
                  </select>
                </li>
                <li>
                  测项：<select name="funcitonId">
                    <option value="" style="display: none">请选择</option>
                  </select>
                </li>
                <li>
                  测点：<select name="pointId" lay-search="">
                    <option value="" style="display: none">请选择</option>
                  </select>
                </li>
                <li class="select-time">
                  <label>创建时间： </label>
                  <input
                    type="text"
                    class="time-input"
                    id="startDate"
                    placeholder="开始时间"
                    name="startDate"
                    style="width: 140px !important;"
                  />
                  <span>-</span>
                  <input
                    type="text"
                    class="time-input"
                    id="endDate"
                    placeholder="结束时间"
                    name="endDate"
                    style="width: 140px !important;"
                  />
                </li>
                <li>
                  <a
                    class="btn btn-primary btn-rounded btn-sm"
                    onclick="querySubmit()"
                    ><i class="fa fa-search"></i>&nbsp;查询</a
                  >
                  <a
                    class="btn btn-warning btn-rounded btn-sm"
                    onclick="exportExcel()"
                    ><i class="fa fa-download"></i>&nbsp;导出</a
                  >
                </li>
              </ul>
            </div>
          </form>
        </div>
        <div class="col-sm-12 select-table table-striped">
          <table id="layui-table" lay-filter="tableFilter"></table>
        </div>
      </div>
    </div>
    <th:block th:include="include :: footer" />
    <script type="text/javascript">
      // layui 初始化
      layui.use("form", function () {
        var laydate = layui.laydate;

        //初始赋值
        laydate.render({
          elem: "#startDate",
          type: "datetime",
          value: getDate("before"),
          isInitValue: true,
        });

        //初始赋值
        laydate.render({
          elem: "#endDate",
          type: "datetime",
          value: getDate(),
          isInitValue: true,
        });
      });

      // 获取日期
      function getDate(type = "current") {
        let date = new Date();

        if (type === "before") {
          // 获取30天前的日期
          date.setTime(date.getTime() - 30 * 24 * 60 * 60 * 1000);
        }

        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        // 补零
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;

        // 添加时分秒
        let time = type === "current" ? "23:59:59" : "00:00:00";

        return year + "-" + month + "-" + day + " " + time;
      }

      var fandArr = [],
        functionArr = [],
        pointArr = [],
        chartType = null;
      var fanId = null,
        funcitonId = null,
        pointId = null;

      // 初始化
      $(function () {
        let fanId = null,
          funcitonId = null,
          pointId = null,
          target = null;

        // 监听项目改变时
        $("[name='fanId']").on("change", function () {
          fanId = $(this).val();
          getCxData(fanId);
        });

        // 监听测项改变时
        $("[name='funcitonId']").on("change", function () {
          chartType = functionArr.find((item) => item.id == $(this).val()).type;
          funcitonId = $(this).val();
          getCdData(fanId, funcitonId);
        });

        // 监听测点改变时
        $("[name='pointId']").on("change", function () {
          pointId = $(this).val();
        });

        // 然后获取数据并手动触发change
        getPorjectData();
      });

      // 获取项目数据
      function getPorjectData() {
        $.ajax({
          url: "commom/getFanListForSensor",
          Type: "post",
          dataType: "json",
          async: false,
          success: (data) => {
            fandArr = [...data];
            let str = "";
            data.forEach((item) => {
              str += `<option value="${item.id}">${item.fanName}</option>`;
            });
            $("[name='fanId']").append(str);
            // 自动选择第一条数据并手动触发change事件
            if (data.length > 0) {
              $("[name='fanId']").val(data[0].id).change();
            }
          },
        });
      }

      // 获取测项数据
      function getCxData(fanId) {
        $.ajax({
          url: "commom/getFunctionListForFan",
          Type: "post",
          data: {
            fanId: fanId,
          },
          dataType: "json",
          async: false,
          success: (data) => {
            functionArr = [...data];
            let str = "";
            data.forEach((item) => {
              str += `<option value="${item.id}">${item.name}</option>`;
            });
            $("[name='funcitonId']").find("option").slice(1).remove();
            $("[name='funcitonId']").append(str);
            // 自动选择第一条数据并手动触发change事件
            if (data.length > 0) {
              $("[name='funcitonId']").val(data[0].id).change();
            } else {
              $("[name='pointId']").find("option").slice(1).remove();
              pointId = null;
            }
          },
        });
      }

      // 获取测点数据
      function getCdData(fanId, funcitonId) {
        $.ajax({
          url: "commom/getPointListForSensor",
          Type: "post",
          data: {
            fanId: fanId,
            functionId: funcitonId,
          },
          dataType: "json",
          async: false,
          success: (data) => {
            pointArr = [...data];
            let str = "";
            data.forEach((item) => {
              str += `<option value="${item.id}">${item.pointName}</option>`;
            });
            $("[name='pointId']").find("option").slice(1).remove();
            $("[name='pointId']").append(str);
            // 自动选择第一条数据
            if (data.length > 0) {
              $("[name='pointId']").val(data[0].id);
              querySubmit();
            }
          },
        });
      }

      // 查询提交
      function querySubmit() {
        const form = document.getElementById("formId");
        const formData = {};
        const elements = form.elements;
        for (let i = 0; i < elements.length; i++) {
          const element = elements[i];
          if (element.name) {
            formData[element.name] = element.value;
          }
        }

        if (!formData.fanId) {
          layer.msg("风机必须选择", { icon: 5 });
          return false;
        }

        if (!formData.funcitonId) {
          layer.msg("测项必须选择");
          return false;
        }

        if (!formData.pointId) {
          layer.msg("测点必须选择", {
            time: 1000,
          });
          return false;
        }

        if (!formData.startDate) {
          layer.msg("开始日期必须选择", {
            time: 1000,
          });
          return false;
        }

        if (!formData.endDate) {
          layer.msg("结束日期必须选择", {
            time: 1000,
          });
          return false;
        }

        // 根据 chartType 切换显示的图表容器
        if (chartType === "ACC") {
          getAccTableData(formData);
        } else {
          getDipTableData(formData);
        }
      }

      // 获取加速度数据
      function getAccTableData(formData) {
        let cols = [
          { field: "createTime", title: "监测时间", width: 150, sort: true },
          { field: "xmean", title: "X方向平均值", width: 150, sort: true },
          { field: "xmin", title: "X方向最小值", width: 150, sort: true },
          { field: "xmax", title: "X方向最大值", width: 150, sort: true },
          { field: "xmean", title: "X方向平均值", width: 150, sort: true },
          { field: "xfre1", title: "X方向主振频率", width: 150, sort: true },
          { field: "xfre2", title: "X方向次振频率", width: 150, sort: true },
          { field: "xfre3", title: "X方向季振频率", width: 150, sort: true },
          { field: "xpow1", title: "X方向主振功率", width: 150, sort: true },
          { field: "xpow2", title: "X方向次振功率", width: 150, sort: true },
          { field: "xpow3", title: "X方向季振功率", width: 150, sort: true },

          { field: "ymean", title: "Y方向平均值", width: 150, sort: true },
          { field: "ymin", title: "Y方向最小值", width: 150, sort: true },
          { field: "ymax", title: "Y方向最大值", width: 150, sort: true },
          { field: "yeff", title: "Y方向有效值", width: 150, sort: true },
          { field: "yfre1", title: "Y方向主振频率", width: 150, sort: true },
          { field: "yfre2", title: "Y方向次振频率", width: 150, sort: true },
          { field: "yfre3", title: "Y方向季振频率", width: 150, sort: true },
          { field: "ypow1", title: "Y方向主振功率", width: 150, sort: true },
          { field: "ypow2", title: "Y方向次振功率", width: 150, sort: true },
          { field: "ypow3", title: "Y方向季振功率", width: 150, sort: true },

          { field: "zmean", title: "Z方向平均值", width: 150, sort: true },
          { field: "zmin", title: "Z方向最小值", width: 150, sort: true },
          { field: "zmax", title: "Z方向最大值", width: 150, sort: true },
          { field: "zeff", title: "Z方向有效值", width: 150, sort: true },
          { field: "zfre1", title: "Z方向主振频率", width: 150, sort: true },
          { field: "zfre2", title: "Z方向次振频率", width: 150, sort: true },
          { field: "zfre3", title: "Z方向季振频率", width: 150, sort: true },
          { field: "zpow1", title: "Z方向主振功率", width: 150, sort: true },
          { field: "zpow2", title: "Z方向次振功率", width: 150, sort: true },
          { field: "zpow3", title: "Z方向季振功率", width: 150, sort: true },
        ];
        // 初始化表格
        initTable("acc/getAccTableList", cols, formData);
      }

      // 获取倾角数据
      function getDipTableData(formData) {
        let cols = [
          { field: "createTime", title: "监测时间", width: 150, sort: true },
          { field: "xmean", title: "X方向平均值", width: 150, sort: true },
          { field: "xmin", title: "X方向最小值", width: 150, sort: true },
          { field: "xmax", title: "X方向最大值", width: 150, sort: true },
          { field: "xeff", title: "X方向有效值", width: 150, sort: true },
          { field: "ymean", title: "Y方向平均值", width: 150, sort: true },
          { field: "ymin", title: "Y方向最小值", width: 150, sort: true },
          { field: "ymax", title: "Y方向最大值", width: 150, sort: true },
          { field: "yeff", title: "Y方向有效值", width: 150, sort: true },
          { field: "zmean", title: "Z方向平均值", width: 150, sort: true },
          { field: "zmin", title: "Z方向最小值", width: 150, sort: true },
          { field: "zmax", title: "Z方向最大值", width: 150, sort: true },
          { field: "zeff", title: "Z方向有效值", width: 150, sort: true },
        ];
        // 初始化表格
        initTable("dip/getDipTableList", cols, formData);
      }

      // 表格初始化
      function initTable(url, cols, formData) {
        layui.use("table", function () {
          var table = layui.table;

          table.render({
            elem: "#layui-table",
            url: url,
            method: "GET",
            where: formData,
            request: {
              pageName: "page",
              limitName: "pageSize",
            },
            page: true,
            page: {
              layout: [
                "count",
                "prev",
                "page",
                "next",
                "limit",
                "refresh",
                "skip",
              ],
              limit: 10,
              limits: [10, 20, 30, 40, 50],
            },
            cols: [cols],
            parseData: function (res) {
              let result = {
                code: 0,
                msg: res.message,
                count: res.data.totalCount,
                data: res.data.list,
              };
              return result;
            },
            done: function (res, curr, count) {
              if (res.code !== 0) {
                layer.msg(res.msg || "数据加载失败");
              }
            },
          });
        });
      }

      // 导出
      function exportExcel() {
        const form = document.getElementById("formId");
        const formData = {};
        const elements = form.elements;
        for (let i = 0; i < elements.length; i++) {
          const element = elements[i];
          if (element.name) {
            formData[element.name] = element.value;
          }
        }

        // 验证表单
        if (
          !formData.fanId ||
          !formData.funcitonId ||
          !formData.pointId ||
          !formData.startDate ||
          !formData.endDate
        ) {
          layer.msg("请完整填写查询条件", { icon: 5 });
          return false;
        }

        // 根据类型选择导出接口
        const url =
          chartType === "ACC" ? "acc/exportAccExcel" : "dip/exportDipExcel";

        // 构建查询字符串
        const queryString = Object.keys(formData)
          .map(
            (key) =>
              `${encodeURIComponent(key)}=${encodeURIComponent(formData[key])}`
          )
          .join("&");

        const xhr = new XMLHttpRequest();
        xhr.open("GET", `${url}?${queryString}`, true);
        xhr.responseType = "blob";

        xhr.onload = function () {
          if (xhr.status === 200) {
            // 检查响应类型
            const contentType = xhr.getResponseHeader("content-type");
            if (contentType && contentType.indexOf("application/json") !== -1) {
              // 处理JSON响应（错误信息）
              const reader = new FileReader();
              reader.onload = function () {
                try {
                  const result = JSON.parse(this.result);
                  layer.msg(result.msg || "导出失败", { icon: 2 });
                } catch (e) {
                  layer.msg("导出失败", { icon: 2 });
                }
              };
              reader.readAsText(xhr.response);
            } else {
              // 处理文件下载
              const blob = new Blob([xhr.response], {
                type: "application/vnd.ms-excel",
              });

              const url = window.URL.createObjectURL(blob);
              const a = document.createElement("a");
              a.href = url;
              a.download = "导出数据_" + new Date().getTime() + ".xlsx";
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              window.URL.revokeObjectURL(url);

              layer.msg("导出成功", { icon: 1 });
            }
          } else {
            layer.msg("导出失败", { icon: 2 });
          }
        };

        xhr.onerror = function () {
          layer.msg("网络连接失败", { icon: 2 });
        };

        xhr.send();
      }
    </script>
  </body>
</html>
